import requests
import pandas as pd
import os
from datetime import datetime, timedelta
import datetime
import json
from wxauto import WeChat

class FangDiCrawler:
    def __init__(self):
        self.csv_path = "house_data.csv"
        # 初始化微信
        self.wx = WeChat()
        # 设置要发送消息的群聊名称
        self.group_name = "上海房产数据闹钟"  # 请替换为实际的群聊名称
        # 检查文件是否存在，不存在则创建带标题的空文件
        '''if not os.path.exists(self.csv_path):
            pd.DataFrame(columns=[
                'sellsumprice', 'sellsumarea', 'sellcount', 
                'data_time', 'update_time', 
                'average_price', 'average_area'
            ]).to_csv(self.csv_path, index=False)
            '''

    def send_to_wechat(self, data_df):
        """发送数据到微信群"""
        if data_df is None or data_df.empty:
            return
        
        # 格式化数据为易读的文本
        message = "🏠 上海房产数据日报\n\n"
        message += f"📅 数据日期：{data_df['data_time'].iloc[0]}\n"
        message += f"⏰ 更新时间：{data_df['update_time'].iloc[0]}\n\n"
        #message += f"💰 销售总价：{data_df['sellsumprice'].iloc[0]:,.2f}元\n"
        #message += f"📐 销售面积：{data_df['sellsumarea'].iloc[0]:,.2f}平方米\n"
        message += f"🏢 销售套数：{data_df['sellcount'].iloc[0]}套\n"
        message += f"💵 平均单价：{data_df['average_price'].iloc[0]:,.2f}元/平方米\n"
        message += f"📏 平均面积：{data_df['average_area'].iloc[0]:,.2f}平方米/套"

        try:
            # 切换到指定的群聊
            self.wx.ChatWith(self.group_name)
            # 发送消息
            self.wx.SendMsg(message)
            print("消息发送成功！")
        except Exception as e:
            print(f"发送消息时发生错误：{e}")

    @staticmethod
    def get_shanghai_house_data():
        """获取上海房产数据"""
        url = "https://www.fangdi.com.cn/oldhouse/getSHYesterdaySell.action"

        headers = {
            "Accept": "application/json, text/javascript, */*; q=0.01",
            "Accept-Encoding": "gzip, deflate, br, zstd",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Connection": "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
            "Cookie": "JSESSIONID=76949564935BA56B1D37A7A725AEB98C; FSSBBIl1UgzbN7N80T=4.F9YROHNuBoH.Gqde3i6P1LGlkjPN4dGaGRF51HygNYA6I0JLCP1YihZq.sy8CuJggT5XnP0Aj5JuBanJMdkk.IIhJWA2GHNugcDa5zsGVHCcoZILLhdcRWmRVYvDtt6ShN8QnPjVDm4oe37rrSiXHeLp1JXijsjMovZTXZhFrN1z4RCGcdnZ15YQ8hiK.HUsoUoJJ0DhKwwWrqlBBa.GDLsL864hmN54cTXxH7gdHWZ9vA19JhutB8YK9XoPQLLCra2ywZA_GgpgfU.CYznELf9F3plCNaCuPi5CnyHj7RKI.K5YsiJEPQoWSRez1Cghcpq5UQYm1A0kkUmcJ0tqLbS4sdGyEUUykS4YbfC3vqPOhwyrlb8HwBsYsMkH7Pb1K3; e5c777bf-df51-4240-90a0-c7ba04a4b424=WyIyMzg0Njg2MjIiXQ; JSESSIONID=76949564935BA56B1D37A7A725AEB98C",
            "Host": "www.fangdi.com.cn",
            "Origin": "https://www.fangdi.com.cn",
            "Referer": "https://www.fangdi.com.cn/old_house/old_house.html",
            "Sec-Ch-Ua": '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
            "Sec-Ch-Ua-Mobile": "?0",
            "Sec-Ch-Ua-Platform": '"macOS"',
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest"
        }

        try:
            # 发送 GET 请求（带 headers）
            response = requests.get(url, headers=headers)
            
            if response.status_code == 200:
                data = response.json()
                # 预处理数据结构
                if isinstance(data, dict):
                    data = [data]  # 将字典转换为列表
                elif not isinstance(data, list):
                    data = []
                data_df=pd.DataFrame(data)
                # 获取当前日期和时间（格式：YYYY-MM-DD HH:MM:SS）
                current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                yesterday_time = (datetime.datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
                
                data_df['data_time']=yesterday_time
                data_df['update_time']=current_time
                data_df['average_price']=data_df['sellsumprice']/data_df['sellsumarea']
                data_df['average_area']=data_df['sellsumarea']/data_df['sellcount']

                print("爬取成功，数据如下：")
                print(data_df)
                return data_df
            else:
                print(f"请求失败，状态码：{response.status_code}")
                print("可能原因：Cookie 过期或反爬机制触发")
        except Exception as e:
            print(f"发生错误：{e}")

if __name__ == "__main__":
    crawler = FangDiCrawler()
    today_data_df = crawler.get_shanghai_house_data()
    #if data_df is not None:
        # 检查文件是否存在，如果不存在则写入header
        #file_exists = os.path.exists("house_data.csv")
        #data_df.to_csv("house_data.csv", mode='a', header=not file_exists, index=False)

    if today_data_df is not None:
        crawler.send_to_wechat(today_data_df)